package org.lansir.af.ui;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.lansir.af.R;
import org.lansir.af.gtalk.providers.AvatarProvider;
import org.lansir.af.gtalk.service.Contact;
import org.lansir.af.gtalk.service.aidl.IChatManager;
import org.lansir.af.gtalk.service.aidl.IXmppFacade;
import org.lansir.af.ui.phone.ChatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ChatListFragment extends CommonFragment {
	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("org.lansir.af", "org.lansir.af.gtalk.GtalkService"));
	}
	
	private IXmppFacade mXmppFacade;
	private IChatManager mChatManager;	
	private ListView lvChatList;
	private boolean mBinded;
	private GtalkServiceConnection mServConn = new GtalkServiceConnection();
	private List<Contact> mChatList;
	private ChatListAdapter mChatListAdapter;
	private LayoutInflater mInflater;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		mChatListAdapter = new ChatListAdapter();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View viewRoot = inflater.inflate(R.layout.chatlist, null);
		lvChatList = (ListView) viewRoot.findViewById(R.id.lvChatlist);
		lvChatList.setAdapter(mChatListAdapter);
		lvChatList.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Contact c = mChatList.get(position);
				Intent i = new Intent(getActivity(), ChatActivity.class);
				i.setData(c.toUri());
				startActivity(i);
			}			
		});
		mInflater = inflater;
		return viewRoot;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (!mBinded)
			mBinded = getActivity().bindService(SERVICE_INTENT, mServConn, Context.BIND_AUTO_CREATE);
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onPause() {
		super.onPause();
		if (mBinded) {
			getActivity().unbindService(mServConn);
			mBinded = false;
		}
		mXmppFacade = null;
	}
	
	/**
	 * The service connection used to connect to the Gtalk service.
	 */
	private class GtalkServiceConnection implements ServiceConnection {

		/**
		 * Constructor.
		 */
		public GtalkServiceConnection() {
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppFacade = IXmppFacade.Stub.asInterface(service);
			try {
					mChatManager = mXmppFacade.getChatManager();
					mChatList = mChatManager.getOpenedChatList();
					mChatListAdapter.notifyDataSetChanged();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {

			mXmppFacade = null;
			mChatManager = null;
			mBinded = false;
		}


	}
	
	
	private class ChatListAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			
			return mChatList == null ? 0 :mChatList.size();
		}

		@Override
		public Object getItem(int position) {

			return mChatList.get(position);
		}

		@Override
		public long getItemId(int position) {

			return mChatList.get(position).hashCode();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.gtalk_contact_list_contact_item, null);
				viewHolder = new ViewHolder();
				viewHolder.ivAvatar = (ImageView) convertView.findViewById(R.id.ivAvatar);
				viewHolder.tvContactlistPseudo = (TextView) convertView.findViewById(R.id.tvContactlistPseudo);
				viewHolder.tvContactlistMsgPerso = (TextView) convertView.findViewById(R.id.tvContactlistMsgPerso);
				convertView.setTag(viewHolder);
			}else{
				viewHolder = (ViewHolder) convertView.getTag();
			}
			bindView(viewHolder, mChatList.get(position));
			return convertView;
		}
		
		private void bindView(ViewHolder viewHolder, Contact curContact) {
			if (curContact != null) {
				viewHolder.tvContactlistPseudo.setText(curContact.getName());
				viewHolder.tvContactlistMsgPerso.setText(curContact.getMsgState());

				String avatarId = curContact.getAvatarId();
				int contactStatus = curContact.getStatus();
				Drawable avatar = getAvatarStatusDrawable(avatarId);
				viewHolder.ivAvatar.setImageDrawable(avatar);
				viewHolder.ivAvatar.setImageLevel(contactStatus);
			}
		}
		
		/**
		 * Get a LayerDrawable containing the avatar and the status icon. The
		 * status icon will change with the level of the drawable.
		 * 
		 * @param avatarId
		 *            the avatar id to retrieve or null to get default
		 * @return a LayerDrawable
		 */
		private Drawable getAvatarStatusDrawable(String avatarId) {
			Drawable avatarDrawable = null;
			if (avatarId != null) {
				Uri uri = AvatarProvider.CONTENT_URI.buildUpon().appendPath(avatarId).build();
				InputStream in = null;
				try {
					try {
						in = getActivity().getContentResolver().openInputStream(uri);
						avatarDrawable = Drawable.createFromStream(in, avatarId);
					} finally {
						if (in != null)
							in.close();
					}
				} catch (IOException e) {
//					Log.w(TAG, "Error while setting the avatar " + avatarId, e);
				}
			}
			if (avatarDrawable == null)
				avatarDrawable = getResources().getDrawable(R.drawable.gtalk_status_icon);
			LayerDrawable ld = (LayerDrawable) getResources().getDrawable(R.drawable.avatar_status);
			ld.setLayerInset(1, 36, 36, 0, 0);
			ld.setDrawableByLayerId(R.id.avatar, avatarDrawable);

			return ld;
		}
		
		private class ViewHolder{
			public ImageView ivAvatar;
			public TextView tvContactlistPseudo;
			public TextView tvContactlistMsgPerso;
		}
		
	}
}
